package com.knife.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.knife.news.logic.NewsService;
import com.knife.news.logic.SiteService;
import com.knife.news.logic.TypeService;
import com.knife.news.logic.impl.NewsServiceImpl;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.logic.impl.TypeServiceImpl;
import com.knife.news.object.News;
import com.knife.news.object.Site;
import com.knife.news.object.Type;
import com.knife.util.CommUtil;

public class GenerateSiteTask extends BackGroundTask{
	/**
	 * 
	 */
	private static final long serialVersionUID = 6505431089540836246L;
	private String sid;
	
	public String getSid() {
		return sid;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}

	SiteService siteDAO = SiteServiceImpl.getInstance();
	TypeService typeDAO = TypeServiceImpl.getInstance();
	NewsService newsDAO = NewsServiceImpl.getInstance();
	HTMLGenerater g;
	Site gsite = new Site();
	List<Type> gtypes=new ArrayList<Type>();
	List<News> allNews=new ArrayList<News>();
	Collection<Object> paras;
	Type gtype = new Type();
	String sql;
	int rows;
	int pageSize;
	int totalPage;
	int nowPage;
	
	public void init(){
		name="generate site";
		gsite = siteDAO.getSiteById(sid);
		gtypes=typeDAO.getAllTypes(sid);
        total = gtypes.size()+1;
		g = new HTMLGenerater(sid);
		//System.out.println("system will generate:"+total+" channel");
	}
	
	protected void work() {
        try {
            Thread.sleep(sleep);
            //System.out.println("system running at:"+counter+"/"+gtypes.size());
            if(counter<gtypes.size()){
	            gtype=gtypes.get(counter);
	            paras = new ArrayList<Object>();
				paras.add(gtype.getId());
				sql = "k_display='1' and k_ispub='1' and k_type=? order by length(k_order) desc,k_order desc";
				allNews = newsDAO.getNews(sql, paras);
				for (News anews : allNews) {
					g.saveNewsToHtml(anews.getId());
				}
				rows = allNews.size();// 总数
				pageSize = CommUtil.null2Int(gtype.getPagenum());// 每页20条
				totalPage = (int) Math.ceil((float) (rows) / (float) (pageSize));// 计算页数
				if(totalPage<1){totalPage=1;}
				for (int i = 0; i < totalPage; i++) {
					nowPage=i+1;
					g.saveTypeListToHtml(gtype.getId(),sql, paras,nowPage,rows);
				}
				System.out.println("generate:"+gtype.getName()+":"+gtype.getHref());
			}else{
				g.saveIndexToHtml();
			}
            counter++;
            sum += counter;
        } catch (InterruptedException e) {
            setRunning(false);
        }
    }
}
